import React,{useState} from 'react'
import { Card,Form,Input, Button, Checkbox,message} from 'antd';
import {useNavigate} from 'react-router'
import logo from 'assets/logo.png'
import request from 'utils/request'
import styles from './index.module.scss'
import { login } from 'api/user';
import { setToken } from 'utils/storage';
export default function Login(props) {
  const navgate = useNavigate() 
  const [loading, setLoading] = useState(false)
  const onFinish = async ({mobile,code}) =>{
   
    setLoading(true)
      try{
        const res = await login(mobile,code)
      //登录成功
      //1.保存token
      setToken(res.data.token)
      //2.跳转到首页
      //3.提示消息
      message.success('登录成功', 1, () => {
        navgate('/home')
      })
      }catch(e){
        
        message.error(e.response.data.message, 1, () => {
          setLoading(false)
        })
      }
  }
  return (
    <div className={styles.login}>
        
    <Card
      className={'login-container'}
    >
       {/* 图片 */}
  <img className={"login-logo"} src={logo} alt="" />
   {/* 表单 */}
   <Form autoComplete="off" size="large" 
   validateTrigger={['onBlur', 'onChange']}
   onFinish={onFinish}
   initialValues={{
    mobile: '13911111111',
    code: '246810',
    agree: true
  }}
   >
    <Form.Item name="mobile"
        rules={[
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式不对',
            validateTrigger: 'onBlur'
          },
          { required: true, message: '请输入手机号' }
        ]}>
      <Input placeholder="请输入手机号" />
    </Form.Item>

    <Form.Item
        name="code"
        rules={[
          { len: 6, message: '验证码6个字符', validateTrigger: 'onBlur' },
          { required: true, message: '请输入验证码' }
        ]}
      >
      <Input placeholder="请输入验证码" />
    </Form.Item>

    <Form.Item
  name="agree"
  valuePropName="checked"
  rules={[
    {
      validator: (rule, value) => {
        if (value === true) {
          // console.log('rule',rule,'value',value);
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请阅读并同意条款和协议'))
        }
      }
    }
  ]}
>
  <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
</Form.Item>
    <Form.Item>
      <Button type="primary" htmlType="submit" block loading={loading}>
        登录
      </Button>
    </Form.Item>
  </Form>
    </Card>
    </div>
  )

}
